import 'dart:collection';
import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/style.dart';
import 'package:group_button/group_button.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/LjgmOrder.dart';
import 'package:shop/shop/life/ServiceDetail.dart';

import 'Login.dart';

/**
 * 服务型店铺的首页
 */
class ServiceIndexPage extends StatefulWidget {
  String mId;//店铺ID
  String merchantTypeId;//店铺类型ID
  ServiceIndexPage({Key key,this.mId,this.merchantTypeId}) : super(key: key);

  @override
  _ServiceIndexPage createState() => _ServiceIndexPage();
}

class _ServiceIndexPage extends State<ServiceIndexPage> {

  String mId;                 //店铺ID
  String merchantTypeId;      //店铺类型ID
  var merchant = {};          //查询的店铺信息
  List mGoodsTypeList = [];   //店铺商品类型集合
  List merchantJishiList=[];  //商户技师集合
  List goodsList = [];        //展示商品集合
  bool guanzhu = false;       //用户是否关注店铺
  String userId;              //用户ID

  // 构造方法
  // _ServiceIndexPage(mId) {
  //   this.mId=mId;
  //   _onLoading(mId);
  // }
  @override
  void initState() {
    // TODO: implement initState
    _onLoading(widget.mId);
    this.merchantTypeId = widget.merchantTypeId;
    this.mId = widget.mId;
    super.initState();
  }

  // 轮播图
  List _imageUrls = []; //定义图片存储的数组
  dynamic funCb;

  // 获取数据
  void _onLoading(mId) async {
    // 此处不能获取上一个页面点击商品的id
    // http://xllm.szghrj.com:8082/app/goods/getGoodsById?gid=1424914810058878977
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userId = prefs.getString("userId");
    String url = "/waimai/merchant/selectMerchantGoods?mId="+mId;
    var x = await HttpUtil().get(url);//得商户信息
    if (x['code'] == 200) {
      merchant = x['data']['merchant'];
      mGoodsTypeList = x['data']['mGoodsTypeList'];
      merchantJishiList = x['data']['merchantJishiList'];
      if(x['data']['merchantPictureList'].length > 0){
        _imageUrls = x['data']['merchantPictureList'];
      }else{
        _imageUrls.add("http://b1-q.mafengwo.net/s9/M00/A5/88/wKgBs1d2ByKAXc2JAACsSNXA-sA34.jpeg");
        _imageUrls.add("http://b1-q.mafengwo.net/s9/M00/A3/F0/wKgBs1d2BFyAceutAADiqnHT0ys50.jpeg");
      }
    }
    //判断用户是否关注该商户
    var y = await HttpUtil().get("/waimai/merchant/merchantGuanzhu?userId="+userId+"&mId="+mId+"&type=0");
    if(y['code']==200){
      guanzhu = y['data'];
    }
    //查询三个展示商品
    // var z = await HttpUtil().get("/waimai/mGoods/getMerchantGoodsFenye?page=1&limit=3&paixu=1&mId="+mId);
    var z = await HttpUtil().get("/waimai/mGoods/getMerchantAllMGoods?mId="+mId+"&paixu=1");
    if(z['code']==200){
      goodsList = z['data'];
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 464, height: 820);
    return new Scaffold(
      appBar: AppBar(
        title: Text("店铺介绍"),
        actions: [//icon: guanzhu ? Icon(Icons.favorite_border,color: Colors.orange,) : Icon(Icons.favorite_border)
          IconButton(icon: guanzhu ? Icon(Icons.star,color: Colors.orange,) : Icon(Icons.star_border) , onPressed: () async {
            var map = new HashMap<String,dynamic>();
            map['mid']=mId;map['type']=0;map['userId']=userId;map['mTypeId']=merchantTypeId;
            Response response = await HttpUtil().post("waimai/mCollect/collect",map);
            var x = json.decode(response.toString());
            if(x['code']==200){
              if(guanzhu){
                guanzhu = false;
              }else{
                guanzhu = true;
              }
            }
            Fluttertoast.showToast(msg: x['msg']);
            setState(() {

            });
          })
        ],
      ),
      body: ListView(
      children: [
        Container(
          // 轮播图
          width: ScreenUtil().setHeight(464),
          height: ScreenUtil().setHeight(232),
          child: Swiper(
            key: UniqueKey(),
            // 解决轮播图片大于3个的问题，是否有效待核实
            itemBuilder: _swiperBuilder,
            itemCount: _imageUrls.length,
            pagination: new SwiperPagination(
              builder: DotSwiperPaginationBuilder(
                color: Colors.black54,
                activeColor: Colors.white,
              )),
            // control: SwiperControl(),
            scrollDirection: Axis.horizontal,
            autoplay: true,
            autoplayDelay: 3000,
            onTap: (index) => print('点击了第$index个'))),
        Container(
          // 店铺信息
          padding: EdgeInsets.all(10),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment
                    .spaceBetween,
                children: [
                  Expanded(child: Container(
                    child: Text(merchant['mname']==null ? "" : merchant['mname'],maxLines: 1,style: TextStyle(color: Colors.red,fontSize: 22),),
                  )),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    child: Text(merchant['placedetail']==null ? "" : merchant['placedetail']),
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    child: merchant['peisongTime']==null || merchant['peisongTime']=="" ? Text("") : Text("营业时间："+merchant['peisongTime']),
                  ),
                  Container(
                      child: merchant['yingyeStatus']==1 ? Text("营业中",style: TextStyle(color: Colors.green),) : Text("休息中",style: TextStyle(color: Colors.red),)
                  )
                ],
              ),
              Container(
                padding: EdgeInsets.fromLTRB(6, 3, 6, 3),
                child: Row(children: [Expanded(
                  child: merchant['jianjie']==null || merchant['jianjie']=="" ? Text("") : Text("店铺介绍："+merchant['jianjie'],
                    style: TextStyle(fontSize: 15),),
                )
                ]),
                decoration: BoxDecoration(),
              ),
            ],
          ),
        ),
        Container(
          padding: EdgeInsets.all(10),
          child: Column(
            children: [
              _getMerchantGoods()
              // GestureDetector(child: Row(
              //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
              //   children: [
              //     Column(
              //       crossAxisAlignment: CrossAxisAlignment.start,
              //       children: [
              //         Container(child: Text("全身精油SPA",style: TextStyle(fontWeight: FontWeight.bold),),),
              //         SizedBox(height: 5,),
              //         Container(child: Text("半年消费100",style: TextStyle(color: Colors.black12),),)
              //       ],
              //     ),
              //     Container(child: Text("预约",style: TextStyle(color: Colors.white),),decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(5)) ,color: Colors.orange,),padding: EdgeInsets.all(5),)
              //   ],
              // ),
              //   behavior: HitTestBehavior.opaque,
              //   onTap: (){
              //   print("预约去");
              //   MyRoute.push(ServiceDetail());
              //   },
              // ),
              // SizedBox(height: 10,),
              // GestureDetector(child: Row(
              //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
              //   children: [
              //     Column(
              //       crossAxisAlignment: CrossAxisAlignment.start,
              //       children: [
              //         Container(child: Text("全身按摩",style: TextStyle(fontWeight: FontWeight.bold),),),
              //         SizedBox(height: 5,),
              //         Container(child: Text("半年消费190",style: TextStyle(color: Colors.black12),),)
              //       ],
              //     ),
              //     Container(child: Text("预约",style: TextStyle(color: Colors.white),),decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(5)) ,color: Colors.orange,),padding: EdgeInsets.all(5),)
              //   ],
              // ),
              //   behavior: HitTestBehavior.opaque,
              //   onTap: (){
              //   print("预约去");
              //   MyRoute.push(ServiceDetail());
              //   },
              // ),
              // SizedBox(height: 10,),
              // GestureDetector(child: Row(
              //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
              //   children: [
              //     Column(
              //       crossAxisAlignment: CrossAxisAlignment.start,
              //       children: [
              //         Container(child: Text("单人香薰全身SPA",style: TextStyle(fontWeight: FontWeight.bold),),),
              //         SizedBox(height: 5,),
              //         Container(child: Text("半年消费100",style: TextStyle(color: Colors.black12),),)
              //       ],
              //     ),
              //     Container(child: Text("预约",style: TextStyle(color: Colors.white),),decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(5)) ,color: Colors.orange,),padding: EdgeInsets.all(5),)
              //   ],
              // ),
              //   behavior: HitTestBehavior.opaque,
              //   onTap: (){
              //   print("预约去");
              //   MyRoute.push(ServiceDetail());
              //   },),
            ],
          ),
        ),
        // 技师展示
        Container(
          padding: EdgeInsets.all(10),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                Text("技师("+merchantJishiList.length.toString()+")"),
                Icon(Icons.chevron_right)
              ],),
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children: [
                    _getMerchantJishi(),
                    // Column(
                    //   children: [
                    //     CachedNetworkImage(imageUrl:"http://img30.360buyimg.com/popWaterMark/jfs/t1972/321/2193771226/74602/4a5786f4/56b447b5N2fc1c043.jpg",height: 100,fit: BoxFit.cover, ),
                    //     Text("罗晓花")
                    //   ],
                    // ),Column(
                    //   children: [
                    //     CachedNetworkImage(imageUrl:"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.alicdn.com%2Fi2%2F671773569%2FTB2lek1npXXXXaXXXXXXXXXXXXX_%21%21671773569.jpg",height: 100,fit: BoxFit.fitWidth, ),
                    //     Text("罗晓花")
                    //   ],
                    // ),Column(
                    //   children: [
                    //     CachedNetworkImage(imageUrl:"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg007.hc360.cn%2Fm7%2FM09%2F53%2F75%2FwKhQo1b4Ry2EEdRMAAAAALulRgg821.jpg",height: 100,fit: BoxFit.cover, ),
                    //     Text("罗晓花")
                    //   ],
                    // ),Column(
                    //   children: [
                    //     CachedNetworkImage(imageUrl:"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg30.360buyimg.com%2FpopWaterMark%2Fjfs%2Ft2287%2F107%2F1648960001%2F184560%2F5d61d9f9%2F56ca7268Na6dafd37.jpg",height: 100,fit: BoxFit.cover, ),
                    //     Text("罗晓花")
                    //   ],
                    // ),
                    // Column(
                    //   children: [
                    //     CachedNetworkImage(imageUrl:"http://img30.360buyimg.com/popWaterMark/jfs/t1972/321/2193771226/74602/4a5786f4/56b447b5N2fc1c043.jpg",height: 100,fit: BoxFit.cover, ),
                    //     Text("罗晓花")
                    //   ],
                    // ),Column(
                    //   children: [
                    //     CachedNetworkImage(imageUrl:"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.alicdn.com%2Fi2%2F671773569%2FTB2lek1npXXXXaXXXXXXXXXXXXX_%21%21671773569.jpg",height: 100,fit: BoxFit.fitWidth, ),
                    //     Text("罗晓花")
                    //   ],
                    // ),Column(
                    //   children: [
                    //     CachedNetworkImage(imageUrl:"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg007.hc360.cn%2Fm7%2FM09%2F53%2F75%2FwKhQo1b4Ry2EEdRMAAAAALulRgg821.jpg",height: 100,fit: BoxFit.cover, ),
                    //     Text("罗晓花")
                    //   ],
                    // ),Column(
                    //   children: [
                    //     CachedNetworkImage(imageUrl:"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg30.360buyimg.com%2FpopWaterMark%2Fjfs%2Ft2287%2F107%2F1648960001%2F184560%2F5d61d9f9%2F56ca7268Na6dafd37.jpg",height: 100,fit: BoxFit.cover, ),
                    //     Text("罗晓花")
                    //   ],
                    // ),
                  ],
                ),
              )
            ],
          ),
        )
      ],
    ));
  }

  _getMerchantGoods(){
    List<Widget> x = [];
    for(int i=0;i<goodsList.length;i++){
      x.add(Container(
        child: Column(
          children: [
            GestureDetector(child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Expanded(child: Text(goodsList[i]['gname'],style: TextStyle(fontWeight: FontWeight.bold),),),
                    Container(
                      width: ScreenUtil().setWidth(360),
                      child: Text(goodsList[i]['gname'],maxLines: 1,style: TextStyle(fontWeight: FontWeight.bold),),
                    ),
                    SizedBox(height: 5,),
                    // Container(child: Text(goodsList[i]['jianjie'],style: TextStyle(color: Colors.black12),),),
                    Container(
                      width: ScreenUtil().setWidth(360),
                      child: Row(
                        children: [
                          Expanded(child: Text(goodsList[i]['jianjie'],style: TextStyle(color: Colors.black38),))
                        ],
                      ),
                    )
                  ],
                ),
                Container(child: Text("预约",style: TextStyle(color: Colors.white),),decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(5)) ,color: Colors.orange,),padding: EdgeInsets.all(5),)
              ],
            ),
              behavior: HitTestBehavior.opaque,
              onTap: (){
                // print("预约去");
                MyRoute.push(ServiceDetail(gid: goodsList[i]['id'],));
              },
            ),
            SizedBox(height: 10,),
          ],
        ),
      ));
    }
    return Container(
      child: Column(children: x),
    );
  }
  
  _getMerchantJishi(){
    List<Widget> x = [];
    for(int i=0;i<merchantJishiList.length;i++){
      x.add(Column(
        children: [
          CachedNetworkImage(imageUrl: Config.getInstance().getHost()+merchantJishiList[i]['picture'],height: ScreenUtil().setHeight(100),width: ScreenUtil().setWidth(90),fit: BoxFit.cover,),
          Text(merchantJishiList[i]['name'])
        ],
      ));
    }
    return Container(
      child: Row(children: x),
    );
  }

  Widget _swiperBuilder(BuildContext context, int index) {
    return (CachedNetworkImage(
      imageUrl: Config.getInstance().getHost()+_imageUrls[index]['picture'],
      fit: BoxFit.fill,
    ));
  }
}